package main

import (
	"fmt"
	"github.com/fvbock/endless"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"io"
	"io/fs"
	"io/ioutil"
	"log"
	"net/http"
	"nt-order/common"
	"nt-order/conf"
	"nt-order/middleware"
	"nt-order/route"
	"os"
	"syscall"
	"time"
)

func main() {
	gin.SetMode(gin.ReleaseMode)
	engine := gin.Default()
	engine.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"POST", "GET"},
		AllowHeaders:     []string{"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With"},
		AllowCredentials: true,
	}))

	initRuntime(engine)

	//系统中间件
	gin.DisableConsoleColor()
	fErr, _ := os.OpenFile(fmt.Sprintf("runtime/log/error-%s.log", time.Now().Format("2006-01-02")), os.O_RDWR|os.O_APPEND|os.O_CREATE, os.ModePerm)
	gin.DefaultErrorWriter = io.MultiWriter(fErr)
	engine.Use(gin.Logger())
	engine.Use(gin.CustomRecovery(func(c *gin.Context, tmp interface{}) {
		if err, ok := tmp.(error); ok {
			common.FailJson(c, 500, err.Error())
		} else if err, ok := tmp.(string); ok {
			common.FailJson(c, 500, err)
		} else {
			common.FailJson(c, 500, "未知错误")
		}
		c.Abort()
	}))
	arr :=make([]string,0)
	x:=[]string{"1","3","1"}
	arr =append(arr,x...)
	fmt.Println(arr)
	fmt.Println(common.RemoveRepeatedElementAndEmpty(arr))
	engine.Use(middleware.CheckListing())
	InitRoute(engine)
	//_ = engine.Run(fmt.Sprintf("%s:%d", conf.Env.Host, conf.Env.Port))

	server := endless.NewServer(fmt.Sprintf("%s:%d", conf.Env.Host, conf.Env.Port), engine)
	server.BeforeBegin = func(add string) {
		log.Printf("Actual pid is %d", syscall.Getpid())
		_ = ioutil.WriteFile("main.pid", []byte(fmt.Sprintf("%d", syscall.Getpid())), fs.ModePerm)
	}
	err := server.ListenAndServe()
	if err != nil {
		log.Printf("Server err: %v", err)
	}

}

func InitRoute(engine *gin.Engine) {
	engine.POST("/", route.Index)
	engine.GET("/", route.Home)
}

func initRuntime(engine *gin.Engine) {
	engine.StaticFS("/export", http.Dir("runtime/export"))
	if !common.FileExist("runtime/export") {
		_ = os.MkdirAll("runtime/export", os.ModePerm)
	}
}
